<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      let arr = [
        { id: 0, name: "1", parent: -1, childNode: [] },
        { id: 1, name: "1", parent: 0, childNode: [] },
        { id: 99, name: "1-1", parent: 1, childNode: [] },
        { id: 111, name: "1-1-1", parent: 99, childNode: [] },
        { id: 66, name: "1-1-2", parent: 99, childNode: [] },
        { id: 1121, name: "1-1-2-1", parent: 112, childNode: [] },
        { id: 12, name: "1-2", parent: 1, childNode: [] },
        { id: 2, name: "2", parent: 0, childNode: [] },
        { id: 21, name: "2-1", parent: 2, childNode: [] },
        { id: 22, name: "2-2", parent: 2, childNode: [] },
        { id: 221, name: "2-2-1", parent: 22, childNode: [] },
        { id: 3, name: "3", parent: 0, childNode: [] },
        { id: 31, name: "3-1", parent: 3, childNode: [] },
        { id: 32, name: "3-2", parent: 3, childNode: [] },
      ];

      function arrTotree(arr, parentId) {
        let result = [];
        const filterArr = arr.filter((item) => {
          if (parentId === undefined) {
            return item.parent === -1;
          } else {
            return item.parent === parentId;
          }
        });
        result = filterArr.map((item) => {
          item.childNode = arrTotree(arr, item.id);
          return item;
        });
        return result;
      }
      console.log(arrTotree(arr));
      //   function arrToTree(arr, parentId) {
      //     // 判断是否是顶层节点，如果是就返回。不是的话就判断是不是自己要找的子节点
      //     const filterArr = arr.filter((item) => {
      //       return parentId === undefined
      //         ? item.parent === -1
      //         : item.parent === parentId;
      //     });
      //     // 进行递归调用把子节点加到父节点的 childNode里面去
      //     filterArr.map((item) => {
      //       item.childNode = arrToTree(arr, item.id);
      //       return item;
      //     });
      //     return filterArr;
      //   }

      //   arrToTree(arr);
      //   console.log(arrToTree(arr));
    </script>
  </body>
</html>
